package com.vanke.devops.domain.domain.users.impl;


import com.vanke.core.login.LoginHelper;
import com.vanke.core.util.CodecUtil;
import com.vanke.devops.dal.dao.UsersMapper;
import com.vanke.devops.dal.model.Users;
import com.vanke.devops.domain.base.BaseServiceImpl;
import com.vanke.devops.domain.domain.users.ICaptchaDomainService;
import com.vanke.devops.domain.domain.users.IUsersService;
import com.vanke.devops.domain.domain.users.dto.UsersDTO;
import com.vanke.devops.domain.enums.SmsOrCaptchaValidationEnum;
import com.vanke.devops.domain.enums.UsersErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;


/**
 * <p>
 * 用户表  服务实现类
 * </p>
 *
 * @author 陈景阳
 * @since 2018-03-11
 */
@Service
public class UsersServiceImpl extends BaseServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private ICaptchaDomainService captchaDomainService;

    @Override
    public UsersDTO login(String loginName, String password, String captcha) {
        captchaDomainService.validateCaptcha(captcha, SmsOrCaptchaValidationEnum.ValidaionType.LOGIN,"captcha");

        if(LoginHelper.login(loginName,CodecUtil.encryptMD5(password))){
           return this.getByLoginName(loginName);
        }
        throw  UsersErrorCode.USER_LOGIN_FAIL.getException();
    }

    @Override
    public UsersDTO getByLoginName(String loginName) {
        Users users = new Users();
        users.setLoginId(loginName);
        Users entity = baseMapper.selectOne(users);
        if(entity == null){
            throw UsersErrorCode.USER_NOT_FOUND.getException();
        }
        return getUsersDTO(entity);
    }

    @Override
    public UsersDTO getById(Integer id) {
        Users entity = baseMapper.selectById(id);
        if(entity == null){
            throw UsersErrorCode.USER_NOT_FOUND.getException();
        }
        return getUsersDTO(entity);
    }

    private UsersDTO getUsersDTO(Users users){
        UsersDTO dto = new UsersDTO();
        dto.setId(users.getId());
        dto.setLoginId(users.getLoginId());
        dto.setUsername(users.getUsername());
        dto.setPassword(users.getPassword());
        return dto;
    }
}